package sseGameApps.service;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import com.google.appengine.api.datastore.Transaction;

import sseGameApps.meta.LoginMeta;
import sseGameApps.model.Login;


public class AuthService {

    private LoginMeta l = new LoginMeta();

    public boolean verifyAuth(String userId, String nowDateTime, Locale reqLocale) {

        List<Login> list = Datastore.query(l).filter(l.userId.equal(userId)).sort(l.userId.asc).asList();

        if (list.size() == 0) {
            return false;
        } else if(list.size() > 1) {
            return false;
        } else {

            Calendar cal = Calendar.getInstance(reqLocale);
            cal.setTime(list.get(0).getLastLoginDate());

            cal.add(Calendar.MINUTE, list.get(0).getPermitTime().intValue());

            TimeZone tz = TimeZone.getTimeZone("JST");
            SimpleDateFormat df =
                new SimpleDateFormat("yyyy/MM/dd HH:mm:ss",reqLocale);
            df.setTimeZone(tz);

            if (nowDateTime.compareTo(df.format(cal.getTime())) > 0){
                return false;
            }

        }

        return true;

    }

    public boolean firstLogin(String userId, String passWord, Date nowDate) {

        Login data = Datastore.query(l).filter(l.userId.equal(userId), l.passWord.equal(passWord)).asSingle();

        if (data == null) {
            return false;
        }

        data.setLastLoginDate(nowDate);

        Transaction tx = Datastore.beginTransaction();
        Datastore.put(data);
        tx.commit();

        return true;
    }

    public boolean registUser(String userId, String passWord, Date nowDate) {

        Login data = Datastore.query(l).filter(l.userId.equal(userId)).asSingle();

        if (data != null) {
            return false;
        }

        data = new Login();
        data.setPassWord(passWord);
        data.setPermitTime(1140);
        data.setUserId(userId);
        data.setLastLoginDate(nowDate);

        Transaction tx = Datastore.beginTransaction();
        Datastore.put(data);
        tx.commit();

        return true;
    }

    public List<Login> getLoginList() {
        return Datastore.query(l).sort(l.userId.asc).asList();
    }

    public void putLogin(Map<String, Object> input) {

        Login data = new Login();
        BeanUtil.copy(input, data);

        Transaction tx = Datastore.beginTransaction();
        Datastore.put(data);
        tx.commit();

    }
}
